import { asyncRoutes } from '@/router'

/**
 * 判断有没有按钮权限
 */
function hasPermission(menus, route) {
  if (route.name) {
    var tempRoute = menus.get(route.name)
    if (tempRoute) {
      return { success: true, name: tempRoute.title, icon: tempRoute.icon }
    } else {
      return { success: false, name: '' }
    }
  } else {
    return { success: false, name: '' }
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, menus) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    var validateResult = hasPermission(menus, tmp)
    if (validateResult.success) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus)
      }
      if (validateResult.name) {
        tmp.meta.title = validateResult.name
        tmp.meta.icon = validateResult.icon
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = routes
  }
}

const actions = {
  generateRoutes(context, roles) {
    return new Promise(resolve => {
      // var menus = context.getters.permission.menus
      // let accessedRoutes = filterAsyncRoutes(asyncRoutes, menus)
      var accessedRoutes = asyncRoutes || []
      context.commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  state,
  mutations,
  actions
}
